<template>
  <div class="h-all flex fd-c">
    <div class="fs-20 flex nodarg ra-10 mr10 ai-c">
      <Select placeholder="年级" @change="initData(1)" clear class="w-100 b-0 hand fs-15 h-35" :data="nianji" v-model="query.grade"></Select>
      <span class="flex-1"></span>
      <page @change="initData" :size="query.size" :total="query.total" :page="query.page"></page>
    </div>
    <div class="w-all mt10 flex-1 nodarg">
      <scroll>
        <div class="w-all pt10 pb10 pr15 flex fw ">
          <div @click="btnShow(item)" v-for="item in info.list" :class="{'scan':item.loading}" style="width:350px;height: 180px;" class="flex hidden rel wrapper ai-c jc-c pt10 fd-c mb10 ml10 pl20 ra-10 glass-card">
            <div class="fs-30 fc-FF4500 fb">{{item.title.en}}</div>
            <span class="fs-20 mt10 fc-000 fb">{{item.title.cn}}</span>
          </div>
        </div>
      </scroll>
    </div>
  </div>

  <div v-if="info.curr" class="fixed flex ai-c sha-card jc-c at0 al0 ab0 ar0 ba-f2">
    <div class="fixed flex ai-c sha-card jc-c at0 al0 ab0 ar0 ba-f2">
      <div style="width:92%;background-color:#14261ee3; padding: 18px 10px 18px 18px; height: 93%;" class="mt20 rel ra-10">
        <div class="flex-line abs zi-140 nodarg al30 at20">
          <Switch v-model="query.isFast" class="fs-18 fc-fff" @change="changeAudio" open="正常,1,#008d1a" close="慢速,2,#ff9900" show></Switch>
        </div>
        <span @click.stop="btnClose" class="iconfont hand nodarg icon-bg-close zi-2000 fc-fff fs-30 abs at10 ar10"></span>
        <span @click="toReading()" v-if="!info.isPlay" class="iconfont icon-bofang1 hand abs nodarg zi-120 fc-success fs-50 ar90 at30"></span>
        <span @click="stopRead()" v-else class="iconfont icon-bofang hand abs nodarg zi-120 fc-danger fs-50 at30 ar90"></span>
        <div class=" w-all  mb10 nodarg custom-scrollbar zi-100  pp5 h-all auto ">
          <!-- <div class="flex ai-c jc-c fd-c">
            <span @click="toReading(info.curr.title.en,info.curr.title)" class="fc-FF4500 nodarg hand fb fs-30">{{info.curr.title.en}} <span class="iconfont icon-ting fs-25 fc-pri "></span> </span>
            <span class="fc-aa fs-16">{{info.curr.title.cn}}</span>
          </div> -->

          <div class="flex fd-c ai-c mt7 jc-c" v-for="item in info.curr.sentences">
            <!-- <span @click="toReading(item.en,item)" class="fc-fff nodarg hand fs-26">{{item.en}} <span class="iconfont icon-ting fs-25 fc-pri "></span></span> -->
            <div :class="{'bc-00fc102b ra-6 pl15 pt5 pb5 pr15':item.select}" class="flex ai-c">
              <span @click="onWordPlay(w.text)" v-copy="w.text" class="mr9 fc-fff nodarg hand fs-26" :class="{'fc-danger':w.select}" v-for="w in item.words">{{w.text}}</span>
              <span @click="onWordPlay(item.text,1,true)" class="iconfont icon-ting hand fs-29 fc-danger"></span>
            </div>
            <span class="fc-aa fs-19">{{item.cn}}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, shallowRef, inject } from 'vue';
const reload = inject('reload') as () => void;
import yy from '@lib/mixin';
import useStore from '../../store';
const nianji = ['三年级', '四年级', '五年级', '六年级', '初一', '初二', '初三']
const st = useStore();
const query = reactive({
  grade: "三年级",
  isFast: 1,//慢，正常
  unit: 1,
  volume: 1,
  page: 1,
  size: 50,
  serch: '',
  total: 0
})
const interval = shallowRef(null);
const currItem = ref(null);
const info = reactive({
  list: [],
  playAudio: null,
  curr: null,
  isPlay: false,
  interval: null,
  isPause: false
})

function changeAudio(v) {
  st.ttsConfig.rate = query.isFast == 2 ? "0.35" : 1;
  if (info.playAudio) {
    info.playAudio.pause();
    info.playAudio = null;
  }
  btnShow()
}

function onWordPlay(word, type = 1, google = false) {
  if (google) {
    const utterance = new SpeechSynthesisUtterance(word);
    utterance.lang = "en-US"; // 设置英语
    window.speechSynthesis.speak(utterance);
    return
  }

  let src = `http://dict.youdao.com/dictvoice?type=${type}&audio=${word}`;
  if (info.playAudio) {
    info.playAudio.pause();
    info.playAudio = null;
  }
  info.playAudio = new Audio(src);
  info.playAudio.volume = 1;
  info.playAudio.play()
}

function stopRead() {
  // debugger;
  console.log(interval.value, '===========');

  info.playAudio.pause();
  info.isPause = true;
  clearInterval(interval.value);
  interval.value = null;
  info.isPlay = false;
}

function btnClose() {
  info.playAudio && info.playAudio.pause();
  info.isPause = true;
  clearInterval(interval.value);
  interval.value = null;
  info.isPlay = false;
  reload();
}

async function btnShow(item) {
  info.isPlay = false;
  info.isPause = false;
  if (item) {
    currItem.value = item;
  } else {
    item = currItem.value;
  }
  let speeks = ` ${item.title.en}. ${item.sentences.map(v => v.en).join(' ')}`;
  // item.loading = true;
  yy.spinner.show();
  st.speek(speeks, { auto: false, word: true, line: true, isFile: true, file: { title: item.title.en, fileUrl: st.fileUrl } }).then(res => {
    // item.loading = false;
    yy.spinner.close();
    res.sentences.map((v, i) => {
      v.cn = i ? item.sentences[i - 1].cn : item.title.cn;
    })
    info.curr = { ...res, title: item.title };
  })
}

function toReading(line) {
  if (line) {
    toPlay(info.curr.url, line)
  } else {
    toPlay(info.curr.url)
  }
}

function setWordHight(next = true) {
  if (!next && info.playAudio) return;
  info.curr?.sentences.forEach(item => {
    item.select = false;
    item.words.forEach(v => v.select = false)
  })
  if (!info.playAudio) return;
  // 高亮句子
  info.curr?.sentences.forEach(item => {
    if (info.playAudio.currentTime >= item.start && info.playAudio.currentTime <= item.end) {
      item.select = true;
      // 句子高亮
      item.words.forEach(v => {
        if (info.playAudio.currentTime >= v.start && info.playAudio.currentTime <= v.end) {
          v.select = true;
        } else {
          v.select = false;
        }
      })
    }
  })
}

function toPlay(url, line) {
  if (!info.isPause) {
    info.playAudio = new Audio(url);
  }
  info.playAudio.play()
  info.isPlay = true;
  const currentTime = 0;
  info.isPause = false;

  info.playAudio.addEventListener('timeupdate', e => {
    let count = 5
    let timer = setInterval(function () {
      if (count == 0) {
        clearInterval(timer)
      } else {
        setWordHight()
        count--;
      }
    }, 50)
  })

  info.playAudio.addEventListener('ended', () => {
    clearInterval(interval.value);
    interval.value = null;
    info.isPause = false;
    info.isPlay = false;
    info.curr.sentences.forEach(item => {
      item.select = false;
      item.words.forEach(v => v.select = false)
    })
    if (info.playAudio) {
      info.playAudio.pause();
      info.playAudio = null;
    }
  })
}

function initData() {
  import(`../../assets/duan-wen/${query.grade}.ts`).then(res => {
    info.list = res.default;
  })
}

initData()
</script>

<style lang='less'>
.bc-00fc102b {
  background-color: #00fc102b;
}
.wrapper {
  &:hover {
    cursor: pointer;
    background-image: url("../../assets/bg.png");
    background-size: cover;
  }
}
</style>